//
//  RequestUntil.m
//  ukongmapp
//
//  Created by ukongm on 16/7/25.
//  Copyright © 2016年 youmeng. All rights reserved.
//

#import "RequestUntil.h"
#import "XFDataModel.h"
#import "AFNetworking.h"
@interface RequestUntil()


@property(nonatomic)NSString* userName;
@property(nonatomic)NSString* device;
/** token */
@property(nonatomic,strong)NSString* token;

/** 保存上传文件的数组 */
@property(nonatomic,strong)NSMutableArray* fileArray;

@end

@implementation RequestUntil

- (NSMutableArray *)fileArray{
    
    if (_fileArray == nil) {
        _fileArray = [NSMutableArray new];
    }
    return _fileArray;
}

- (NSString *)device
{
//    _device = [UserInfo shared].deviceId;
    
//    IS_NULL(_device);
    
    return _device;
}

- (NSString *)userName
{
//    _userName =  [UserInfo shared].data.username;
//    IS_NULL(_userName);
    return self.appDelegate.user.memberId;
}

- (NSString *)token
{
//    _token = [UserInfo shared].data.token;
//    IS_NULL(_token);
    return self.appDelegate.user.token;
}

- (NSMutableString *)paramStr
{
    if (_paramStr == nil) {
        _paramStr = [[NSMutableString alloc]init];
    }
    
    return _paramStr;
}

- (NSMutableDictionary *)dict
{
    if (_dict == nil) {
        _dict = [NSMutableDictionary new];
    }
    return _dict;
}

- (void)setComplateBlockForSuccess:(success)successComplate fail:(fail)failComplate handle:(handle)handleComplate{
    self.successComplate = successComplate;
    self.failComplate = failComplate;
    self.handleComplate = handleComplate;
}

- (instancetype)initWithBool:(BOOL)isInit
{
    if (self = [super init]) {
        if (isInit) {
            
            [self addParam:self.userName andKey:@"member_id"];
//            [self addParam:self.device andKey:@"device"];
            [self addParam:self.token andKey:@"token"];
        }
        
        [self addParam:@"pad" andKey:@"app_v"];
    }
    return self;
}

- (void)addParam:(NSString *)value andKey:(NSString *)key
{
    if (value == nil) {
        value = @"";
    }
    
    if (self.paramStr.length == 0) {
        [self.paramStr appendFormat:@"%@=%@",key,value];
    }
    else
    {
        [self.paramStr appendFormat:@"&%@=%@",key,value];
    }
    
    [self.dict setObject:value forKey:key];
}

- (void)postWithSubPath:(NSString *)subPath andMark:(NSString *)mark
{
    NSURLSession* session = [NSURLSession sharedSession];
    
    NSString* urlStr = [NSString stringWithFormat:@"%@%@",MAIN_URL,subPath];
    
    NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:urlStr]];
    
    request.HTTPMethod = @"POST";
    request.HTTPBody = [self.paramStr dataUsingEncoding:NSUTF8StringEncoding];
    
    XFLog(@"%@?%@",urlStr,self.paramStr);
    
    NSURLSessionDataTask* task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        //在主线程执行一段代码
        [ThreadManager handleCodeForMain:^{
            if (error) {
                //这里的if主要用于判断这个代理对象是否接受代理并重写的协议方法
                [self failForError:error mark:mark];
            }
            else
            {
                
                [self successForData:data mark:mark];
            }
            
            [self handleForMark:mark];
        }];
    }];
    
    [task resume];
}

#pragma mark - 文件相关
- (void)addParam:(NSData *)data andKey:(NSString *)key fileName:(NSString *)fileName type:(NSString *)type{
    XFDataModel* model = [XFDataModel new];
    model.data = data;
    model.key = key;
    model.fileName = fileName;
    model.type = type;
    [self.fileArray addObject:model];
}

- (void)uploadWithSubPath:(NSString *)subPath contentType:(NSSet *)set mark:(NSString *)mark{
    AFHTTPSessionManager* manager = [[AFHTTPSessionManager alloc]init];
    //返回的对象是data
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", nil];
    manager.responseSerializer.acceptableContentTypes = set;
    
    NSString* urlStr = [MAIN_URL stringByAppendingString:subPath];
    
    XFLog(@"%@?%@",urlStr,self.paramStr);
    
    [manager POST:urlStr parameters:self.dict constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        //遍历所有的文件
        for (XFDataModel* model in self.fileArray) {
            
//            NSData* dataStr = [model.data base64EncodedDataWithOptions:NSDataBase64EncodingEndLineWithCarriageReturn];
            
            [formData appendPartWithFileData:model.data name:model.key fileName:model.fileName mimeType:model.type];
            
        }
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self successForData:responseObject mark:mark];
        
        [self handleForMark:mark];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [self failForError:error mark:mark];
        
        [self handleForMark:mark];
    }];
    
}

#pragma mark - 调用协议相关
- (void)failForError:(NSError*)error mark:(NSString*)mark{
    
    if (self.failComplate) {
        self.failComplate(error,mark);
    }else{
        if (self.delegate && [self.delegate respondsToSelector:@selector(fail:andMark:)]) {
            
            [self.delegate fail:error andMark:mark];
        }
    }
}

- (void)successForData:(NSData*)data mark:(NSString*)mark{
    if (self.successComplate) {
        self.successComplate(data,mark);
    }else{
        if (self.delegate && [self.delegate respondsToSelector:@selector(succeed:andMark:)]) {
            
            [self.delegate succeed:data andMark:mark];
            
        }
    }
}

- (void)handleForMark:(NSString*)mark{
    if (self.handleComplate) {
        self.handleComplate(mark);
    }else{
        if (self.delegate && [self.delegate respondsToSelector:@selector(handle)]) {
            
            [self.delegate handle];
            
        }
    }
}

@end

@implementation ThreadManager

+ (void)handleCodeForMain:(void (^)())block
{
    dispatch_async(dispatch_get_main_queue(), block);
}

+ (void)handleCodeForAsync:(void (^)())block
{
    dispatch_queue_t queue = dispatch_queue_create("xf", DISPATCH_QUEUE_CONCURRENT);
    
    dispatch_async(queue, block);
}

+ (void)handleCodeForTime:(CGFloat)time andTimer:(void (^)(dispatch_source_t timer))block{
    
    static dispatch_source_t timer;
    
    if (timer) {
        dispatch_cancel(timer);
    }
    
    timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());
    dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, time * NSEC_PER_SEC, 1 * NSEC_PER_SEC);
    dispatch_source_set_event_handler(timer, ^{
       
        block(timer);
        
    });
    dispatch_resume(timer);
}

@end



